package jacker.bit.price;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;


public class ActivityPrices2 extends Activity {
	
	String threadid;
	String prevthrd;
	String nextthrd;
	
	ListView pricelist;
	TextView titlev;
    //List<DtoMail> emails = new ArrayList<DtoMail>();
    
    //BaseAdapter adp0;
    
    PriceHelper mh ;
	PriceHelper mh2 ;
	Cursor cursor = null;
	SimpleCursorAdapter adp0;
	//Map<Long,DtoMail> cache = new HashMap<Long,DtoMail>();
	
    
    Drawable failicon;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.prices);
        //AdCtrl.showAd(this);
        threadid = getIntent().getStringExtra(Consts.EXTRA_THREADID);
        
        failicon = getApplicationContext().getResources().getDrawable(android.R.drawable.presence_busy);
        failicon.setBounds(new Rect(0,0,16,16));
        
        mh = new PriceHelper(this);
        mh2 = new PriceHelper(this);
        
        pricelist = (ListView)findViewById(R.id.prices);
        titlev = (TextView)findViewById(R.id.price_title);
        
        CurrentPrice cp = mh2.getCurrentPrice(threadid);
        titlev.setText(cp.getThreadname());
      
        adp0 = new SimpleCursorAdapter(this,R.layout.price
        		,cursor,new String[]{},new int[]{}){
        	@Override
        	public void bindView(View itemView,Context context, Cursor cur){
        		super.bindView(itemView, context, cur);
        		Price price = setPrice(cur);
        		
        		//TextView namev = (TextView)itemView.findViewById(R.id.threadname);
				 TextView pricev = (TextView)itemView.findViewById(R.id.price);
				 TextView datev = (TextView)itemView.findViewById(R.id.pricedate);
				 ImageView img = (ImageView)itemView.findViewById(R.id.photo);
				 
				// namev.setText(price.getThreadid());
				 pricev.setText(price.getCurrency()+UtilString.price(price.getPrice()));
				datev.setText(UtilString.getDateStr(price.getDate()));
				if(price.getAlarm()>=0)
					img.setImageResource(R.drawable.up);
				else
					img.setImageResource(R.drawable.down);

        	}
        	};
         
        pricelist.setAdapter(adp0);
        
        
        pricelist.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View view, int index,
					long arg3) {
				
				
			}
        	
        });
        
                
        PriceHelper.registerObserver(processhandler);
        
        
        refreshView();
        
        
    }

    
    private void hideButtons(){
    	//prev.setVisibility(View.GONE);
    	//next.setVisibility(View.GONE);
    	//compose.setVisibility(View.GONE);
    }
    

    private void refreshView(){
		android.os.Message msg = new android.os.Message();
		msg.what = Consts.MSG_DATA_UPDATE;
		processhandler.sendMessage(msg);
	}
    
    Handler processhandler = new Handler(){
		@Override
    	public void handleMessage(android.os.Message msg) {
			if(msg.what == Consts.MSG_DATA_UPDATE){
				getPrices();
				return;
			}
			
/*			if(msg.what == Consts.MSG_DATA_UPDATE){
				android.os.Message mes = new android.os.Message();
				mes.what = Consts.MSG_UI_UPDATE;
				processhandler.sendMessageDelayed(mes, 200);
				return;
			}*/
			
		}
	};
	
	Price pricetemp = new Price(); //avoid multi thread
	private Price setPrice(Cursor cur){
    	pricetemp.setSid(cur.getLong(0));
    	pricetemp.setThreadid(cursor.getString(1));
    	pricetemp.setPrice(cursor.getFloat(2));
    	pricetemp.setDate(cur.getLong(3));
    	pricetemp.setAlarm(cursor.getInt(4));
    	pricetemp.setCurrency(cursor.getString(5));
    	return pricetemp;
    }
	
	private Price getPrice(int position){
		cursor.moveToPosition(position);
		return mh2.getPrice(cursor.getLong(0));
	}
    
	public void getPrices(){
    	UtilLog.d("load thread...");
    	
    	cursor = mh.getWritableDatabase().query("PRICES"
    			, new String[]{"sid _id","threadid","price","pricedate","alarm","currency"}
				, "threadid=?", new String[]{threadid}
				, null, null
				, "pricedate desc");
    	
    	//if(cursor.getCount()==0){
		//	releaseFinish();
		//	return;
		//}
		
		
		adp0.changeCursor(cursor);
        adp0.notifyDataSetChanged();
		
		
	}
    
    @Override
    public void onBackPressed(){
    	release();
    	super.onBackPressed();
    }
    
    private void release(){
    	PriceHelper.removeObserver(processhandler);
    	
    	if(cursor!=null && !cursor.isClosed())
    		cursor.close();
    	
    	mh.getWritableDatabase().close();
    }
    
    private void releaseFinish(){
    	release();
    	finish();
    }

    private Price getFirst(){
    	return getPrice(0);
    }
    
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(Menu.NONE,Consts.MENU_DELETE,60,R.string.delete_action)
			.setIcon(android.R.drawable.ic_menu_delete);

		return true;
	}
	
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==5){
			//MailReceiver.checkMails(this,false);
			getPrices();
			return true;
		}else if(item.getItemId()==Consts.MENU_DELETE){
			AlertDialog.Builder builder = new AlertDialog.Builder(this); //use this, not ctx
			builder.setTitle(R.string.delete_action);
			builder.setMessage(getString(R.string.clear_local_folder_action));
			builder.setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					new PriceHelper(ActivityPrices2.this).deletePrices(threadid);
					
				}
				
			});
			builder.setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
				
			});
			builder.show();
			
			return true;
		}
		return false;
	}


    
}